
from model import PasswordAssistant
from dzutil import include
from dzpage import Page
from dzmail import SendMail
import time

class Controller:

    def _request_password_reset_button(self,**args):

        r = PasswordAssistant(**args)

        errors = r.errors
        if errors:
            for item in errors:
                warning(item)
        else:
            r.token  = zoomer.session.new_session()  # session module generates unique tokens
            r.expiry = time.time() + 3600  # one hour
            r.put()
            return self.send_reset_message(r.email,r.token)

    def send_reset_message(self,address,token):

        body       = include('activate.txt') % dict(site_name=zoomer.name,reset_link=url_for(action='request',token=token))
        returnaddr = 'Password Assistance <%s>' % zoomer.config.get('site','register_email')

        try:
            SendMail(returnaddr,address,'%s Assistance' % zoomer.name,body,'html')
        except:
            zoomer.log.log('D','Error sending password reset %s to %s' % (newsid,webvars.email))
            return Page(include('register_error.txt'))
        else:
            zoomer.log.log('D','Password reset sent to %s with token %s' % (address,token))
            return Page(include('step2.txt') % dict(site_name=zoomer.name))

    def _request(self,token):
        rlist = PasswordAssistant.find(token=token)
        if rlist:
            r = rlist[0]

            if r.expired():
                return Page(include('expired.txt') % dict(site_name=zoomer.name,register_link=url_for(action=zoomer.app.name)))

            else:
                import render
                return render.render(inline=include('reset_parameter.txt') % dict(site_name=zoomer.name,username=r.username,first_name=r.first_name,token=token))

    def _confirm(self,token,PASSWORD,CONFIRM):
        rlist = PasswordAssistant.find(token=token)
        if rlist:
            r = rlist[0]

            if r.expired():
                return Page(include('expired.txt') % dict(site_name=zoomer.name,reset_link=url_for(app=zoomer.app.name)))

            elif PASSWORD <> CONFIRM:
                message('Passwords do not match.  Please try again.')

            else:
                r.set_password(PASSWORD)
                return Page(include('complete.txt') % dict(site_name=zoomer.name,reset_link=url_for(action=zoomer.app.name)))


result = Controller()